package cn.cqie.attendance.teacher.service.impl;

import cn.cqie.attendance.common.dao.AttachmentMapper;
import cn.cqie.attendance.common.pojo.Attachment;
import cn.cqie.attendance.common.util.DateUtil;
import cn.cqie.attendance.common.util.LocalJwt;
import cn.cqie.attendance.common.util.Page;
import cn.cqie.attendance.common.util.PageBean;
import cn.cqie.attendance.teacher.dao.TeacherHomeworkDao;
import cn.cqie.attendance.teacher.pojo.*;
import cn.cqie.attendance.teacher.service.TeacherHomeworkService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wqh
 * @date 2021/7/6 12:39
 */
@Service
public class TeacherHomeworkServiceImpl implements TeacherHomeworkService {

    @Autowired
    private TeacherHomeworkDao teacherHomeworkDao;
    @Autowired
    private AttachmentMapper attachmentDao;
    @Autowired
    private HttpServletRequest request;
    //当前登录教师id
    //int teacherId = 1;

    @Override
    public PageBean<TeacherHomeworkRes> queryHomeworkInfoByTeacherId(TeacherHomeworkReq param) {
        int teacherId = LocalJwt.getCurrentUserId(request);
        param.setTeacherId(teacherId);
        if (param.getPageNum() == null || param.getPageSize() == null){
            param.setPageNum(1);
            param.setPageSize(10);
        }
        PageBean pageBean = new PageBean();
        pageBean.setPageNum(param.getPageNum());
        pageBean.setPageSize(param.getPageSize());
        PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
        List<TeacherHomeworkRes> homeworkResList = teacherHomeworkDao.queryHomeworkInfoByTeacherId(param);
        int total = homeworkResList.size();
        if (null == homeworkResList || total == 0) {
            return new PageBean<>(500,"查询数据为空");
        }
        return new PageBean<>(200, "Success",homeworkResList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Page insertHomeworkInfo(InsertHomeworkReq param) throws ParseException {
        int teacherId = LocalJwt.getCurrentUserId(request);
        Date date = DateUtil.getNowFormatDate("yyyy-MM-dd HH:mm:ss");
        param.setPublishTime(date);
        param.setTeacherId(teacherId);
        //新增发布作业（publishHomework）
        int count = teacherHomeworkDao.insertHomeworkInfo(param);
        if (count > 0){
            //返回发布作业主键
            int publishHomeworkId = param.getId();
            //获得小组ID列表
            String groupId = param.getGroupId();
            //获得学生ID列表
            String stuId = param.getStuId();
            //分配作业斐具体学生
            if (groupId.contains(",")){
                String[] g = groupId.split(",");
                String[] s = stuId.split(",");
                int len = s.length;
                int i;
                for(i = 0;i < len;i ++){
                    Map<String,Object> map = new HashMap<>();
                    map.put("groupId",g[i]);
                    map.put("stuId",s[i]);
                    map.put("status",0);
                    map.put("publishHomeworkId",publishHomeworkId);
                    teacherHomeworkDao.insertHomeworkByStudentId(map);
                }
                if (i == len){
                    return Page.SUCCESS;
                }else {
                    return Page.FAIL;
                }
            }else {
                String[] s = stuId.split(",");
                int len = s.length;
                int i;
                for(i = 0;i < len;i ++){
                    Map<String,Object> map = new HashMap<>();
                    map.put("groupId",groupId);
                    map.put("stuId",s[i]);
                    map.put("status",0);
                    map.put("publishHomeworkId",publishHomeworkId);
                    teacherHomeworkDao.insertHomeworkByStudentId(map);
                }
                if (i == len){
                    //上传附件
                    String address = param.getAddress();
                    Attachment attachment = new Attachment();
                    attachment.setAddress(address);
                    attachment.setPublishHomeworkId(publishHomeworkId);
                    attachment.setType(0);
                  int countA =  attachmentDao.insert(attachment);
                  if (countA > 0){
                      return Page.SUCCESS;
                  }else {
                      return Page.FAIL;
                  }
                }else {
                    return Page.FAIL;
                }
            }
        }else {
            return Page.FAIL;
        }
    }
    /*@Override
    public Page insertHomeworkByStudentId(String groupId,String stuId,Integer publishHomeworkId) {
        if (groupId.contains(",")){
            String[] g = groupId.split(",");
            String[] s = stuId.split(",");
            int len = s.length;
            int i;
            for(i = 0;i < len;i ++){
                Map<String,Object> map = new HashMap<>();
                map.put("groupId",g[i]);
                map.put("stuId",s[i]);
                map.put("status",0);
                map.put("publishHomeworkId",publishHomeworkId);
                teacherHomeworkDao.insertHomeworkByStudentId(map);
            }
            if (i == len){
                return Page.SUCCESS;
            }else {
                return Page.FAIL;
            }
        }else {
            String[] s = stuId.split(",");
            int len = s.length;
            int i;
            for(i = 0;i < len;i ++){
                Map<String,Object> map = new HashMap<>();
                map.put("groupId",groupId);
                map.put("stuId",s[i]);
                map.put("status",0);
                map.put("publishHomeworkId",publishHomeworkId);
                teacherHomeworkDao.insertHomeworkByStudentId(map);
            }
            if (i == len){
                return Page.SUCCESS;
            }else {
                return Page.FAIL;
            }
        }
    }*/

    @Override
    public Page<CourseListRes> queryCourseByTeacherId() {
        int teacherId = LocalJwt.getCurrentUserId(request);
        List<CourseListRes> resList = teacherHomeworkDao.queryCourseByTeacherId(teacherId);
        return new Page<>(200,"Success",resList);
    }

    @Override
    public Page<GroupListRes> queryGroupsByCourseId(Integer courseId) {
        List<GroupListRes> resList = teacherHomeworkDao.queryGroupsByCourseId(courseId);
        return new Page<>(200,"Success",resList);
    }

    @Override
    public Page<StudentListRes> queryStudentsByGroupId(String[] groupIds) {
        List<StudentListRes> resList = teacherHomeworkDao.queryStudentsByGroupId(groupIds);
        return new Page<>(200,"Success",resList);
    }

   /* @Override
    public Page insertHomeworkAttachment(String address, Integer type, Integer publishHomeworkId) {
        Map<String,Object> map = new HashMap<>();
        map.put("address",address);
        map.put("type",type);
        map.put("publishHomeworkId",publishHomeworkId);
        int count = teacherHomeworkDao.insertHomeworkAttachment(map);
        if (count > 0){
            return Page.SUCCESS;
        }else {
            return Page.FAIL;
        }
    }*/

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Page deleteHomeworkById(Integer id) {
        int countP = teacherHomeworkDao.deleteHomeworkByPublishHomeworkId(id);
        if (countP > 0){
            int count = teacherHomeworkDao.deleteHomeworkById(id);
            if (count > 0){
                    return Page.SUCCESS;
                }else {
                    return Page.FAIL;
                }
        }else {
            return Page.FAIL;
        }
    }

    @Override
    public PageBean queryHomeworkReplyByStatus(ReplyHomeworkReq param) {
        int teacherId = LocalJwt.getCurrentUserId(request);
        param.setTeacherId(teacherId);
        if (param.getPageNum() == null || param.getPageSize() == null){
            param.setPageNum(1);
            param.setPageSize(10);
        }
        PageBean pageBean = new PageBean();
        pageBean.setPageNum(param.getPageNum());
        pageBean.setPageSize(param.getPageSize());
        PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
        List<ReplyHomeworkRes> resList = teacherHomeworkDao.queryHomeworkReplyByStatus(param);
        int total = resList.size();

        if (null == resList || total == 0) {
            return new PageBean(500,"查询数据为空");
        }
        return new PageBean(200, "Success",resList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Page updateHomeworkById(float score, String replyContent, Integer homeworkId,String address) {
        Map<String, Object> map = new HashMap<>();
        map.put("score",score);
        map.put("replyContent",replyContent);
        map.put("id",homeworkId);
        int count = teacherHomeworkDao.updateHomeworkById(map);
        if (count > 0){
            Attachment attachment = new Attachment();
            attachment.setType(2);
            attachment.setAddress(address);
            attachment.setHomeworkId(homeworkId);
            int countA = attachmentDao.insert(attachment);
            if (countA > 0){
                return Page.SUCCESS;
            }else {
                return Page.FAIL;
            }
        }else {
            return Page.FAIL;
        }
    }

    @Override
    public Page<HomeworkAnswer> queryHomeworkAnswerById(Integer homeworkId) {
        List<HomeworkAnswer> list = teacherHomeworkDao.queryHomeworkAnswerById(homeworkId);
        if(null == list){
            return Page.FAIL;
        }else {
            return new Page(200,"Success",list);
        }
    }

    @Override
    public Page queryHomeworkDetailById(Integer id) {
       List<HomeworkDetail> list = teacherHomeworkDao.queryHomeworkDetailById(id);
       int count = list.size();
       if (count > 0){
           return new Page(200,"Success",list);
       }else {
           return new Page(999,"查询列表为空！");
       }
    }

    @Override
    public Page<TeacherHomeworkSet> queryHomeworkSetById(Integer homeworkId) {
        List<TeacherHomeworkSet> list = teacherHomeworkDao.queryHomeworkSetById(homeworkId);
        if (list == null){
            return Page.FAIL;
        }else {
            return new Page(200,"Success",list);
        }
    }
}
